<script setup>
import { ref, watch } from 'vue';
import { getCurrentInstance } from 'vue';
import { uploadArticleContentImgService } from '@/api/forumArticle';

// markdown相关
import VMdEditor from '@kangc/v-md-editor/lib/codemirror-editor';
import '@kangc/v-md-editor/lib/style/codemirror-editor.css';
import githubTheme from '@kangc/v-md-editor/lib/theme/github.js';
import '@kangc/v-md-editor/lib/theme/style/github.css';
// highlightjs
import hljs from 'highlight.js';
// codemirror 编辑器的相关资源
import Codemirror from 'codemirror';
// mode
import 'codemirror/mode/markdown/markdown';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/mode/css/css';
import 'codemirror/mode/htmlmixed/htmlmixed';
import 'codemirror/mode/vue/vue';
// edit
import 'codemirror/addon/edit/closebrackets';
import 'codemirror/addon/edit/closetag';
import 'codemirror/addon/edit/matchbrackets';
// placeholder
import 'codemirror/addon/display/placeholder';
// active-line
import 'codemirror/addon/selection/active-line';
// scrollbar
import 'codemirror/addon/scroll/simplescrollbars';
import 'codemirror/addon/scroll/simplescrollbars.css';
// style
import 'codemirror/lib/codemirror.css';

VMdEditor.Codemirror = Codemirror;
VMdEditor.use(githubTheme, {
  Hljs: hljs,
});

// Vue实例
const { proxy } = getCurrentInstance()

// 父级传递过来的参数
const props = defineProps({
  modelValue: { // 文章内容
    type: String,
    default: "",
  },
  mode: {
    type: String,
    default: "editable",
  },
  height: {
    type: Number,
    default: 500,
  }
})

// 父级方法
const emit = defineEmits(['setHtmlContent', 'update:modelValue'])
// 内容变化时触发的事件。mdContent为输入的内容，htmlContent为解析之后的 html 字符串。
const change = (mdContent, htmlContent) => {
  // 在Vue3中，update:modelValue 是v-model指令的默认事件，用于在组件内部通知父组件更新绑定的值
  emit("update:modelValue", mdContent)
  // 触发父级事件，将文本编辑器中内容返回给父级，最后插入到数据库中
  emit("setHtmlContent", htmlContent)
}

// 文章内容图片上传
const uploadImageHandler = async (event, insertImage, files) => {
  // 先将图片上传到服务器上
  let result = await uploadArticleContentImgService({
    file: files[0],
  })
  console.log("文件上传结果", result)

  // 这里需要把获取的图片传递回父级页面中，新增文章
  insertImage({
    url: result.data,
    desc: "图片",
  })
}
</script>

<template>
  <v-md-editor :model-value="modelValue" :mode="mode" :height="height + 'px'" :disabled-menus="[]"
    :include-level="[1, 2, 3, 4, 5, 6]" @upload-image="uploadImageHandler" @change="change"></v-md-editor>
</template>

<style></style>